﻿using UnityEngine;
using Raven;

public class GameController : MonoBehaviour, IQueryTime
{
    public float timeScale = 1;
    public float time = 0;

    private RavenGame _ravenGame;


    void Start()
    {
        //Raven.Logger.Set(Debug.Log, Debug.LogWarning, Debug.LogError);
        DisplayObjectFactory.SetDisplayCreator(EntityType.Wall, typeof(Wall2DDisplay));
        DisplayObjectFactory.SetDisplayCreator(EntityType.Bot, typeof(BotDisplay));
        DisplayObjectFactory.SetDisplayCreator(EntityType.SpawnPoint, typeof(SpawnPointDisplay));
        DisplayObjectFactory.SetDisplayCreator(EntityType.Grave, typeof(GraveDisplay));
        DisplayObjectFactory.SetDisplayCreator(EntityType.Bolt, typeof(BoltDisplay));
        DisplayObjectFactory.SetDisplayCreator(EntityType.RailGunWeaponGiver, typeof(WeaponGiverDisplay));
        DisplayObjectFactory.SetDisplayCreator(EntityType.RocketLauncherWeaponGiver, typeof(WeaponGiverDisplay));
        DisplayObjectFactory.SetDisplayCreator(EntityType.ShotgunWeaponGiver, typeof(WeaponGiverDisplay));
        DisplayObjectFactory.SetDisplayCreator(EntityType.Health, typeof(HealthDisplay));
        DisplayObjectFactory.SetDisplayCreator(EntityType.Slug, typeof(SlugDisplay));
        DisplayObjectFactory.SetDisplayCreator(EntityType.Rocket, typeof(RocketDisplay));
        DisplayObjectFactory.SetDisplayCreator(EntityType.Pellet, typeof(PelletDisplay));

        _ravenGame = new RavenGame(this);
        ResizeWindow();
    }

    // Update is called once per frame
    void Update()
    {
        time += Mathf.Min(Time.deltaTime, 1.0f / Constants.FrameRate);
        _ravenGame.GetTimer().SetTimerScale((FixConst) timeScale);
        _ravenGame.Update();
    }

    void ResizeWindow()
    {
        if (Camera.main == null)
        {
            return;
        }

        float sizeX = _ravenGame.GetSizeX();
        float sizeY = _ravenGame.GetSizeY();

        Camera camera = Camera.main;
        camera.orthographic = true;

        float aspect = sizeX / sizeY;
        if (aspect < camera.aspect)
        {
            camera.orthographicSize = sizeY / 2.0f;
        }
        else
        {
            camera.orthographicSize = (sizeY / 2.0f) * (aspect / camera.aspect);
        }

        camera.transform.position = new Vector3(sizeX / 2.0f, sizeY / 2.0f, camera.transform.position.z);
    }

    public Fix GetTime()
    {
        return (FixConst) time;
    }
}